<?php
namespace app\admin\model;

use think\Model;

class BlogArticle extends Model
{
    /**
     * @param int $cid 文章分类, 空则获取所有文章
     * @param int $page 列表第几页
     * @param int $num_of_per 每页多少条
     * @param int $top 是否推荐 0 or 1 or 2
     * @param int $satus 是否上线 0(所有) or 1(正常) or 2(下线)
     * @param string $field 查询字段 默认 'id,cid,title,pubtime,summary,clicks'
     * @param mixed $order 排序规则 数组或字符串, 默认  ['sort' => 'desc','id' => 'desc',];
     * @return array $data 包含模型对象和条数等的多维数组
     */
    public function getLists($cid=null, $page = 1, $num_of_per = 12, $top = 0, $status = 1, $map = [], $field = '', $order = null)
    {
        $map['isdel'] = 0;

        $cid ? $map['cid'] = $cid : '';
        $top ? $map['top'] = $top : '';
        $status ? $map['status'] = $status : '';
        $field ? '' : $field  = 'id,cid,title,pubtime,summary,clicks';

        if (!$order) {
            $order = [
                'sort' => 'desc',
                'id' => 'desc',
            ];
        }

        $data = [];

        $counts = $this->where($map)->count('id');
        $pages = intval(ceil($counts / $num_of_per));

        $lists = $this->where($map)
            ->field($field)
            ->order($order)
            ->limit(($page - 1) * $num_of_per, $num_of_per)
            ->select();

        $count = count($lists);

        $data = [
            'counts' => $counts,
            'pages' => $pages,
            'count' => $count,
            'num_of_per' => $num_of_per,
            'lists' => $lists,
        ];

        return $data;
    }

    /**
     * 获取分类 Top one 数据一条
     * @param int $cid  分类 id
     * @return object $data 模型的对象实例
     */
    public function getTopOne($cid)
    {
        $data = $this->field('id, title, summary, pubtime')
            ->where(['top'=>2, 'status'=>1, 'isdel'=>0, 'cid'=>$cid])
            ->order('sort desc')
            ->find();

        return $data;
    }

    /**
     * 获取数据一条
     * @param int $id  分类 id
     * @return object $data 模型的对象实例
     */
    public function getOne($id)
    {
        $data = $this->where(['status'=>1, 'isdel'=>0])->find($id);
        $this->save(['clicks'=>$data['clicks']+1], ['id'=>$id]);
        return $data;
    }
}
